package com.bml.architect.netty.reconnection;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

public class ReConnNettyClient {

    private static Bootstrap bootstrap;

    private String ip;
    private int port;

    public ReConnNettyClient(String ip, int port) {
        this.ip = ip;
        this.port = port;

    }

    private void init() {
        EventLoopGroup clientGoup = new NioEventLoopGroup();
        final ReConnNettyClient client = this;
        bootstrap = new Bootstrap();
        bootstrap.group(clientGoup)
                .channel(NioSocketChannel.class)// 使用 NioSocketChannel 作为客户端的通道实现
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReConnNettyClientHandler(client));
                    }
                });
        try {
            connec();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {

        ReConnNettyClient client = new ReConnNettyClient("127.0.0.1", 8000);
        client.init();

    }

    public void connec() throws InterruptedException {

        ChannelFuture connect = bootstrap.connect("127.0.0.1", 8000);
        connect.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    future.channel().eventLoop().schedule(() -> {
                        System.err.println("服务器断开，自动重连");
                        try {
                            connec();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }, 3, TimeUnit.SECONDS);
                } else {
                    System.out.println("服务器连接成功");
                }
            }
        });
        connect.channel().closeFuture().sync();
    }


}